package com.cg;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @author cheyinbo
 * @description TODO
 * @date 2021/8/18 12:11
 */
public class CglibProxy {
    public static void main(String[] args) {
        CglibTeacherDao cglibTeacherDao = new CglibTeacherDaoImpl();
        CglibProxyFactory cglibProxyFactory = new CglibProxyFactory(cglibTeacherDao);
        CglibTeacherDao proxyInstance = (CglibTeacherDao) cglibProxyFactory.getProxyInstance();
        System.out.println(proxyInstance.getClass());
        System.out.println(proxyInstance.teach("张老师"));
    }
}

interface CglibTeacherDao {

    String teach(String teacherName);
}

class CglibTeacherDaoImpl implements CglibTeacherDao {

    @Override
    public String teach(String teacherName) {
        return teacherName + "正在教课...";
    }
}

class CglibProxyFactory {

    private final Object target;

    public CglibProxyFactory(Object target) {
        this.target = target;
    }

    public Object getProxyInstance() {
        return Enhancer.create(target.getClass().getSuperclass(), target.getClass().getInterfaces(), new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                System.out.println("代理开始");
                Object invoke = method.invoke(target, objects);
                System.out.println("代理技术");
                return invoke;
            }
        });
    }

}
